package com.ajview.core.security.handler;

import com.ajview.common.core.domain.bo.LoginUser;
import com.ajview.common.core.domain.enums.ResultCodeEnum;
import com.ajview.common.core.domain.vo.ResultVo;
import com.ajview.common.utils.DateUtils;
import com.ajview.common.utils.ServletUtils;
import com.ajview.core.security.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ZhangJunJie
 * @Date 2022-04-30
 * <p>
 * 概要：退出登录
 */
@Component
@Slf4j
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {
    @Resource
    private TokenService tokenService;

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String token = tokenService.getToken(request);
        LoginUser loginUser = tokenService.getLoginUser(token);
        if (!ObjectUtils.isEmpty(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getTokenUUID());
            log.info("用户：{}，在{}时，退出登录", userName, DateUtils.getTime());
        }
        ServletUtils.renderString(response, ResultVo.result(ResultCodeEnum.LOGOUT_SUCCESS).toString());
    }
}
